/*
 *  Copyright 2008 The MITRE Corporation (http://www.mitre.org/). All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */


package org.mitre.lattice.taglib;

import org.mitre.mrald.util.MetaData;import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;

import org.mitre.lattice.lattice.InsufficentGroupAccessException;
import org.mitre.lattice.lattice.InvalidLatticeStructureException;
import org.mitre.lattice.lattice.LatticeErrorHandler;
import org.mitre.lattice.lattice.LatticeException;
import org.mitre.lattice.lattice.LatticeFunctions;
import org.mitre.lattice.lattice.LatticeNode;
import org.mitre.lattice.lattice.NodeNotFoundException;
import org.mitre.lattice.lattice.NullLatticeNodeException;
import org.mitre.lattice.query.GroupList;
import org.mitre.mrald.util.Config;
import org.mitre.mrald.util.MiscUtils;
import org.mitre.mrald.util.MraldConnection;
import org.mitre.mrald.util.MraldException;
import org.mitre.mrald.util.MraldOutFile;
import org.mitre.mrald.util.User;

/**
 *@author     Gail Hamilton
 *@created    November 4, 2003
 */

public class GroupListTag extends TagSupport
{

	/**
	 *  Description of the Field
	 */
	public final static String KEY = GroupListTag.class.getName();
	private String keyGroup = "Public";
	private String listOnly = "false";


	/**
	 *  Constructor for the AllTablesListTag object
	 */
	public GroupListTag() {

		MraldOutFile.logToFile(Config.getProperty("LOGFILE"), "GroupListTag : Start " );

	}


	/**
	 *  Gets the body attribute of the BuildForm object
	 *
	 *@param  keyGroup                             Description of the Parameter
	 *@return                                      The body value
	 *@exception  NodeNotFoundException            Description of the Exception
	 *@exception  InsufficentGroupAccessException  Description of the Exception
	 *@exception  MraldException                   Description of the Exception
	 */
	public String getGroups(String keyGroup)
		 throws NodeNotFoundException, InsufficentGroupAccessException, MraldException
	{

		this.keyGroup = keyGroup;
		GroupList groupList = new GroupList();

		/*
		 *  Produce the table names with the appropriately labeled checkboxs
		 */
		StringBuffer buffer = new StringBuffer();

		ArrayList allGroups = new ArrayList();

		allGroups = (ArrayList) groupList.getGroups(keyGroup);

		java.util.List allGroupsSorted = LatticeFunctions.sort(allGroups);

		buffer.append(outputGroups((ArrayList) allGroupsSorted));

		return buffer.toString();
	}


	/**
	 *  Gets the body attribute of the BuildForm object
	 *
	 *@return                                       The body value
	 *@exception  InsufficentGroupAccessException   Description of the Exception
	 *@exception  NodeNotFoundException             Description of the Exception
	 *@exception  NullLatticeNodeException          Description of the Exception
	 *@exception  InvalidLatticeStructureException  Description of the Exception
	 *@exception  MraldException                    Description of the Exception
	 */
	public String getGroups()
		 throws InsufficentGroupAccessException, NodeNotFoundException, NullLatticeNodeException, InvalidLatticeStructureException, MraldException
	{

		GroupList groupList = new GroupList();

		/*
		 *  Produce the table names with the appropriately labeled checkboxs
		 */
		StringBuffer buffer = new StringBuffer();

		ArrayList allGroups = new ArrayList();

		allGroups = (ArrayList) groupList.getGroups("");

		buffer.append(outputGroups(allGroups));

		return buffer.toString();
	}


	/**
	 *  Gets the body attribute of the BuildForm object
	 *
	 *@param  allGroups                             Description of the Parameter
	 *@return                                       The body value
	 *@exception  InsufficentGroupAccessException   Description of the Exception
	 *@exception  NodeNotFoundException             Description of the Exception
	 *@exception  NullLatticeNodeException          Description of the Exception
	 *@exception  InvalidLatticeStructureException  Description of the Exception
	 *@exception  MraldException                    Description of the Exception
	 */
	public String outputGroups(ArrayList allGroups)
		 throws InsufficentGroupAccessException, NodeNotFoundException, NullLatticeNodeException, InvalidLatticeStructureException, MraldException
	{

		/*
		 *  Produce the table names with the appropriately labeled checkboxs
		 */
		StringBuffer buffer = new StringBuffer();

		buffer.append("\n<tr><th colspan=\"2\"></th></tr><td><b>Current COI:</b></td><td><b>" + keyGroup + "</b></td></tr>");

		buffer.append("\n<tr><th colspan=\"2\"></th></tr>");
		String groupName = null;

		for (int i = 0; i < allGroups.size(); i++)
		{
			groupName = ((LatticeNode) allGroups.get(i)).getName().toString();
			buffer.append("\n<tr>");
			buffer.append("<td width=12 align='center' colspan=\"2\">" + groupName + "</td>");
			buffer.append("</tr>");
		}

		return buffer.toString();
	}


	/**
	 *  Description of the Method
	 *
	 *@return                   Description of the Return Value
	 *@exception  JspException  Description of the Exception
	 */
	public int doStartTag()
		 throws JspException
	{
		HttpServletRequest req = (HttpServletRequest) pageContext.getRequest();

		try
		{
			String modify = req.getParameter("ModifyNode");
			String groupList = null;

			//just want a straight listing
			if (listOnly.equals("true"))
			{

				String coi = "Public";
				Connection conn = new MraldConnection(MetaData.ADMIN_DB).getConnection();
				Statement stmt = conn.createStatement();
				User user = (User) pageContext.getSession().getAttribute(Config.getProperty("cookietag"));
				String email = user.getEmail();

				ResultSet rs = stmt.executeQuery("Select latticegroupid from people where email = '" + email + "'");
				if (rs.next())
				{
					coi = rs.getString(1);
				}
				rs.close();
				stmt.close();
				conn.close();

				pageContext.getOut().print(selectGroups(coi));
				return 0;
			}

			if (modify == null)
			{
				groupList = process(req);
			} else if (modify.equals("Focus") || (modify.equals("Unfocus")))
			{
				groupList = process(req);
			} else
			{
				GroupModifyListTag groupListTag = Config.getLatticeFactory().getGroupModifyListTag();
				groupList = groupListTag.process((HttpServletRequest) pageContext.getRequest());
			}
			pageContext.getOut().print(groupList);

		} catch (NullPointerException e)
		{
			//In this case force the user to login

			HttpServletResponse resp = (HttpServletResponse) pageContext.getResponse();
			try
			{
				resp.sendRedirect(Config.getProperty("BaseUrl") + "/LatticeLogin.jsp?pageurl=" + req.getRequestURL());
			} catch (IOException ie)
			{
				JspException se = new JspException(ie);
				throw se;
			}
		} catch (IOException ie)
		{
			JspException se = new JspException(ie);
			throw se;
		} catch (JspException e)
		{
			JspException se = new JspException(e);
			throw se;
		} catch (MraldException e)
		{
			JspException se = new JspException(e);
			throw se;
		}
		catch (SQLException e)
		{
			JspException se = new JspException(e);
			throw se;
		}
		return 0;
	}


	/**
	 *  Description of the Method
	 *
	 *@param  email               Description of the Parameter
	 *@return                     Description of the Return Value
	 *@exception  MraldException  Description of the Exception
	 */
	private String selectGroups(String groupName)
		 throws MraldException
	{
		StringBuffer rtnBuf = new StringBuffer();


		GroupList grpList = new GroupList();
		ArrayList groups = (ArrayList) grpList.getChildren(groupName);
		rtnBuf.append("<br><b>Select COI    </b><SELECT name='COI'>");
		for (int i = 0; i < groups.size(); i++)
		{
			String latticeGroup = ((LatticeNode) groups.get(i)).getName();
			rtnBuf.append("<OPTION value=\"" + MiscUtils.checkApostrophe(latticeGroup) + "\">" + latticeGroup + "</OPTION>");
		}
		rtnBuf.append("</SELECT>");

		return rtnBuf.toString();
	}


	/**
	 *  Description of the Method
	 *
	 *@param  req               Description of the Parameter
	 *@return                   Description of the Return Value
	 *@exception  JspException  Description of the Exception
	 */
	public String process(HttpServletRequest req)
		 throws JspException
	{
		try
		{
			init();

			StringBuffer groupList = new StringBuffer();
			User user = (User) req.getSession().getAttribute(Config.getProperty("cookietag"));
			String keyGroup = null;
			try
			{
				keyGroup = user.getGroup();

			} catch (NullPointerException e)
			{
				throw e;
			}

			boolean showWholeLattice = false;
			String modifyLattice = req.getParameter("ModifyNode");

			if (modifyLattice == null)
			{
				showWholeLattice = false;
			} else if (modifyLattice.equals("Unfocus"))
			{
				showWholeLattice = true;
				groupList.append("<input type=\"hidden\" name=\"showLattice\" value=\"1\">\n");
			}

			if (showWholeLattice)
			{

				groupList.append(getGroups());
			} else
			{
				if (keyGroup != null)
				{

					groupList.append(getGroups(keyGroup));
				}
			}

			return groupList.toString();
		} catch (NodeNotFoundException e)
		{
			LatticeException latticeErr = null;
			latticeErr = e;
			LatticeErrorHandler.handleException(null, latticeErr, true);
		} catch (InsufficentGroupAccessException e)
		{
			LatticeException latticeErr = null;
			latticeErr = e;
			LatticeErrorHandler.handleException(null, latticeErr, true);
		} catch (MraldException e)
		{
			JspException se = new JspException(e);
			throw se;
		}
		return null;
	}


	/**
	 *  Sets the keyGroup attribute of the GroupListTag object
	 *
	 *@param  listOnly  The new listOnly value
	 */
	public void setListOnly(String listOnly)
	{
		this.listOnly = listOnly;
	}


	/**
	 *  Sets the keyGroup attribute of the GroupListTag object
	 *
	 *@param  keyGroup  The new keyGroup value
	 */
	public void setKeyGroup(String keyGroup)
	{
		this.keyGroup = keyGroup;
	}


	/**
	 *  Initializes the Lattice
	 */

	public void init()
	{
	}
}

